import datetime
import json

import requests
from django.contrib.auth.backends import ModelBackend
import re

from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from bangwodai.settings import MEDIA_URL
from users.models import Users, VerifyCode
from users.serializers import UserDetailSerializer


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    :token  返回的jwt
    :user   当前登录的用户信息[对象]
    :request 当前本次客户端提交过来的数据
    """
    head_img = None
    if str(user.head_img) != "":
        head_img = MEDIA_URL + str(user.head_img)
    return {
        'token': token,
        'id': user.id,
        'username': user.username,
        'role_type': user.role_type,
        'head_img': head_img,
        'status_code': 200,
        # 'user': UserDetailSerializer(user, context={'request': request}).data
    }


def get_user_by_account(account):
    """
    根据帐号获取user对象
    :param account: 账号，可以是用户名，也可以是手机号
    :return: Users对象 或者 None
    """
    user = None
    try:
        if re.match('^1[3-9]\d{9}$', account):
            # 帐号为手机号
            user = Users.objects.get(phone=account)
        elif re.match('^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', account):
            # 账号为邮箱
            user = Users.objects.get(email=account)
        else:
            # 帐号为用户名
            user = Users.objects.get(username=account)
    except Users.DoesNotExist:
        user = None
    finally:
        return user

#验证用户提交的短信和我们保存在数据库里的信息是否一致
def sms_code_verify(phone, code):
    # 登录验证
    verify_records = VerifyCode.objects.filter(phone=phone).order_by("-add_time")

    if verify_records:
        # 最近的一个验证码
        last_record = verify_records[0]
        # 有效为5分钟
        five_minutes_ago = datetime.datetime.now() - datetime.timedelta(hours=0, minutes=5, seconds=0)
        if five_minutes_ago < last_record.add_time and last_record.code == code:
            # return True
            return True
        # return False
        if five_minutes_ago > last_record.add_time:
            raise serializers.ValidationError({"err_msg": "验证码过期", "status_code": 400})

        if last_record.code != code:
            # 说明输入的验证码是错误的 和数据中匹配不上
            return serializers.ValidationError({"err_msg": "验证码错误", "status_code": 400})
    else:
        serializers.ValidationError({"err_msg": "请确认手机号", "status_code": 400})

class UsernameMobileEmailAuthBackend(ModelBackend):
    """
    自定义用户名、邮箱或手机号认证或验证码登录
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        # # try:
        # user = get_user_by_account(username)
        # # 当密码长度为4时，我判断其为手机号和短信验证码登录
        # if len(password) == 4 and user is not None and sms_code_verify(username, password):
        #     return user
        # elif user is not None and user.check_password(password):
        #     return user
        # else:
        #     return None

        if username is None:
            raise serializers.ValidationError("用户名不能为空")
        if password is None:
            raise serializers.ValidationError("密码不能为空")
        user = get_user_by_account(username)
        if user is None:
            raise serializers.ValidationError("用户不存在")
        if user is not None and user.check_password(password):
            return user
        if user is not None and not user.check_password(password):
            raise serializers.ValidationError("密码错误")